package com.qf.utils.filter;

import com.qf.bean.Employee;
import com.qf.bean.Menu;
import com.qf.bean.Role;
import com.qf.dao.EmployeeMapper;
import com.qf.dao.MenuMapper;
import com.qf.dao.RoleMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;

/**
 * IntelliJ IDEA -> person
 * 2019/11/26 16:35
 *
 * @author zmyao
 * 别看，我是渣渣。
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权开始");
        Employee employee =(Employee) principalCollection.getPrimaryPrincipal();
        Role role = roleMapper.selectByPrimaryKey(employee.getRoleid());
        SimpleAuthorizationInfo  info =new SimpleAuthorizationInfo();
        info.addRole(role.getRname());
        List<Menu> menus = menuMapper.selectPermissionByRoleId(role.getRoleid());
        ArrayList<String> permissionList = new ArrayList<>();
        for (Menu menu : menus) {
            permissionList.add(menu.getProcode());
        }
        info.addStringPermissions(permissionList);
        System.out.println("授权结束");
        return info;
    }
//认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证开始");
        String username = (String)authenticationToken.getPrincipal();
        Employee employee = employeeMapper.login(username);
        if (employee == null ){
            System.out.println("认证结束1");
            return  null;
        }
        else {
            System.out.println("认证结束2");
            return new SimpleAuthenticationInfo(employee,employee.getLoginpassword(), ByteSource.Util.bytes(employee.getSalt()),"myrealm");
        }

    }
}
